package com.example.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

//全局异常处理器
@ControllerAdvice(annotations = {RestController.class, Controller.class})//添加了@RestController和@Controller会被处理器处理
@ResponseBody
@Slf4j
public class AllExceptionHandler {
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)//处理这个异常
    private R<String> exceptionhandler(SQLIntegrityConstraintViolationException exception)
    {
        if(exception.getMessage().contains("Duplicate entry"))//信息里是否包含Duplicate entry
        {
            String[] s = exception.getMessage().split(" ");
            String err=s[2]+"已存在";
            return R.error(err);
        }
        return R.error("未知错误");
    }

    @ExceptionHandler(CustomerExcaption.class)//处理这个异常
    private R<String> exceptionhandler(CustomerExcaption exception)
    {
        return R.error(exception.getMessage());
    }
}
